﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;
using VPLink2014.Data;
using VPLink2014.Data.Notifications;

namespace VPLink2014
{
    public partial class CalculNotifications : LayoutsPageBase
    {
        private bool itemHasBeenSeen(NewsItem item)
        {
            bool res = true;
            DateTime? lastModifiedDate = item.LastModified.ToSmallDateTime("dd/MM/yyyy HH:mm:sss", "fr-FR");
            DateTime? lastVisitedDate = item.LastVisited.ToSmallDateTime("dd/MM/yyyy HH:mm:sss", "fr-FR");
            if (lastModifiedDate != null && lastVisitedDate != null)
            {
                res = lastModifiedDate.Value.CompareTo(lastVisitedDate) > 0 ? false : true;
            }
            return res;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string workspaceName = this.Request.QueryString[QueryStringParam.WorkspaceName];
            string userAccount = Context.User.Identity.Name;
            int notifsCount = 0;
            string responseJson = "{}";
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (VPLinkLogConnection db = new VPLinkLogConnection())
                    {
                        Notification dbNotifs = db.VplinkEntities.GetUserNotifications(userAccount);
                        if (dbNotifs != null)
                        {
                            NotificationsItem userNotifs = FileSerialization.CreateObjFromXMLString<NotificationsItem>(dbNotifs.XmlNotifications);
                            WorkSpace workspace = userNotifs.WorkSpaces.Where(x => x.Name.Equals(workspaceName)).FirstOrDefault();
                            if (workspace != null)
                            {
                                workspace.NewsSources
                                    .ForEach(source => notifsCount += source.listItems.Where(item => !itemHasBeenSeen(item)).Count());
                            }
                        }
                    }
                });
                responseJson = string.Format(@"{{""notifCount"" : ""{0}""}}", notifsCount.ToString().ToJson());
                Response.Write(responseJson);
                Response.End();
            }
            catch (System.Threading.ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                responseJson = string.Format(@"{{""messageError"" : ""{0}"", ""stackTrace"" : ""{1}""}}", ex.Message.ToJson(), ex.StackTrace.ToJson());
                Response.Write(responseJson);
                Response.End();
            }
        }
    }
}
